package com.changli02.tcpudp;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPTest1 {
    @Test
    public void client() {
        Socket socket = null;

        OutputStream os = null;
        try {
            InetAddress inet = InetAddress.getByName("10.151.166.121");
            int port = 8089;
            socket = new Socket(inet,port);

            os = socket.getOutputStream();
            os.write("你好，我是客户端！".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os != null){
                    os.close();
                }
                if(socket!=null){
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    @Test
    public void server() {
        ServerSocket serverSocket = null;
        InputStream is = null;
        try {
            serverSocket = new ServerSocket(8089);

            Socket accept = serverSocket.accept();
            System.out.println("服务端已开启.......");
            System.out.println("收到了来自"+accept.getInetAddress()
                    .getHostAddress()+"的连接");
            is = accept.getInputStream();

            byte [] Buffer = new byte[1024];

            int len ;
            while ((len = is.read(Buffer))!=-1){
                String s = new String(Buffer,0,len);
                System.out.println(s);
            }
            System.out.println("数据接收完毕....");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (serverSocket !=null)
                    serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is !=null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
